<template>
  <static-content-wrapper
      :designer="designer" :field="field" :design-state="designState"
      :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
      :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">
    <el-form-item class="noMargin" >
      <div style="">
        <span style="color:#409EFF;cursor: pointer;user-select:none;width: 99vw;"  @click="btn">
         <i class="el-icon-circle-plus-outline" ></i>
         <span>添加一行</span>
        </span>
        <el-table
            ref="elTables"
            :data="fieldModel"
            :border="true"
        >
          <el-table-column
              v-for="item in field.options.tablesOBJ"
              :key="item.dataKey"
              :prop="item.dataKey"
              :label="item.title"
              align="center"
              :width="item.tableWidth">
            <!--          这里如何自定义为input输入框-->
            <template v-slot="scope">
              <el-input v-model="scope.row[item.dataKey]" style="text-align: center !important;"></el-input>
            </template>
          </el-table-column>

          <el-table-column
              label="操作"
              align="center"
              width="100">
            <template v-slot="scope">
              <el-button @click="del(scope.$index)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      <el-button @click="btn">添加一行</el-button>-->
      <!--      <el-button @click="getData">获取数据</el-button>-->
    </el-form-item>
  </static-content-wrapper>
</template>

<script>
import StaticContentWrapper from '@/components/form-designer/form-widget/field-widget/static-content-wrapper'
import emitter from '@/utils/emitter'
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin"
import {deepClone} from "@/utils/util";

export default {
  name: "tableForm-widget",
  componentName: 'FieldWidget',  // 必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },
  },
  watch: {
    'field.options.tablesOBJ': {
      handler(newValue) {
        // console.log('field.options.tablesOBJ 变化了:', newValue);

        // 创建一个新的 field.options.defaultValue 数组，逐行处理
        let updatedTableData = [];

        // 遍历现有的 field.options.defaultValue 行
        this.fieldModel.forEach(row => {
          let newRow = {};

          // 遍历新的 newValue，保留已有的值，并添加新列
          newValue.forEach(item => {
            newRow[item.dataKey] = row[item.dataKey] || '';
          });

          updatedTableData.push(newRow);
        });

        // 如果有新增列，添加新的空数据行
        if (newValue.length > this.fieldModel[0].length) {
          let newRow = {};
          newValue.forEach(item => {
            newRow[item.dataKey] = '';
          });
          updatedTableData.push(newRow);
        }

        // 更新 tableData 和 spanData
        this.fieldModel = updatedTableData;
        this.spanData = newValue.map(item => item.dataKey);

        // console.log('更新后的tableData', this.fieldModel);
        // console.log('spanData', this.spanData);
      },
      deep: true, // 监听嵌套对象的变化
      immediate: true // 立即执行 handler
    }
  },
  data() {
    return {
      tableData: [
        {name1719904802: '', name1719904805: '', name1719904811: ''}
      ],
      spanData:[],
      fieldModel: [{name1719904802: '', name1719904805: '', name1719904811: ''}],
    }
  },
  components: {
    StaticContentWrapper,
  },
  created() {
    this.registerToRefList()
    this.initEventHandler()
    this.initFieldModel()
    console.log('打印', this.field.options)
  },
  beforeDestroy() {
    this.unregisterFromRefList()
  },
  methods: {
    del(scope,e){
      // console.log('删除打印',scope,e,this.fieldModel)
      if(this.fieldModel.length==1){
        this.$message.error('至少保留一行数据')
        return
      }
      this.fieldModel.splice(scope, 1);
    },
    initFieldModel() {
      if (!this.field.formItemFlag) {
        return
      }

      if (!!this.subFormItemFlag && !this.designState) {  //SubForm子表单组件需要特殊处理！！
        let subFormData = this.formModel[this.subFormName]
        if (((subFormData === undefined) || (subFormData[this.subFormRowIndex] === undefined) ||
                (subFormData[this.subFormRowIndex][this.field.options.name] === undefined)) &&
            (this.field.options.defaultValue !== undefined)) {
          this.fieldModel = this.field.options.defaultValue
          subFormData[this.subFormRowIndex][this.field.options.name] = this.field.options.defaultValue
        } else if (subFormData[this.subFormRowIndex][this.field.options.name] === undefined) {
          this.fieldModel = null
          subFormData[this.subFormRowIndex][this.field.options.name] = null
        } else {
          this.fieldModel = subFormData[this.subFormRowIndex][this.field.options.name]
        }

        /* 主动触发子表单内field-widget的onChange事件！！ */
        setTimeout(() => {  //延时触发onChange事件, 便于更新计算字段！！
          this.handleOnChangeForSubForm(this.fieldModel, this.oldFieldValue, subFormData, this.subFormRowId)
        }, 800)
        this.oldFieldValue = deepClone(this.fieldModel)

        this.initFileList()  //处理图片上传、文件上传字段

        return
      }

      if ((this.formModel[this.field.options.name] === undefined) &&
          (this.field.options.defaultValue !== undefined)) {
        this.fieldModel = this.field.options.defaultValue
      } else if (this.formModel[this.field.options.name] === undefined) {  //如果formModel为空对象，则初始化字段值为null!!
        this.formModel[this.field.options.name] = null
      } else {
        this.fieldModel = this.formModel[this.field.options.name]
      }
      this.oldFieldValue = deepClone(this.fieldModel)
      this.initFileList()  //处理图片上传、文件上传字段
      // console.log('打印初始化model',this.fieldModel,typeof(this.fieldModel))
    },
    // handleCloseCustomEvent() {
    //   if (this.field.options.onClose) {
    //     let changeFn = new Function(this.field.options.onClose)
    //     changeFn.call(this)
    //   }
    // }
    btn(){
      // console.log('打印model',this.fieldModel,typeof(this.fieldModel))
      let newRow = {};
      this.spanData.forEach(dataKey => {
        newRow[dataKey] = '';
      });

      // 将新行添加到 tableData
      this.fieldModel.push(newRow);
      // console.log('提交数据',this.tableData)
      // console.log('查看tablesOBJ',this.field.options.tablesOBJ)
    },
    getData(){
      alert(JSON.stringify(this.tableData))
    }
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-input input{
  text-align: center;
}
.noMargin{
  //background: chocolate;
  ::v-deep .el-form-item__content{
    margin-left: 0!important;
    width: 100%;
  }
  ::v-deep .el-table__inner-wrapper{
    width: 100%;
  }
}
</style>
